<?php
/**
 * Created by Administrator
 * User: longli
 * VX: isa1589518286
 * Date: 2020/12/08
 * Time: 21:03
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\cus;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\SysCountries;
use app\common\model\CsEmailCategory;
use app\common\model\CsEmailTemplate;
use app\common\model\Orders;
use app\common\service\cus\EmailService;
use think\facade\Validate;

class EmailtempController extends BaseController
{
    /**
     * 分类列表
     * @return string|string[]
     * @date 2020/12/08
     * @author longli
     */
    public function index()
    {
        $this->loadCommon();
        if(!$this->request->isAjax()) return $this->fetch('index');
        $model = CsEmailTemplate::with(['category', 'country'])->order("sort desc, status desc,temp_id desc");
        // 处理搜索
        $this->searchModel($model, [
            'eq' => ['cate_id', 'lang'],
            'like' => ['subject', 'content', 'keyword'],
            'times' => ['create_time']
        ]);
        $limit = $this->getPageSize();
        $ret = $model->paginate($limit);
        $this->assign('list', $ret->getCollection());
        $this->assign('page', $ret->render());
        return $this->fetch('lists');
    }

    /**
     * 复制邮件模板
     * @date 2020/12/10
     * @author longli
     */
    public function copy()
    {
        $sn = $this->request->request("sn", "", "trim");
        $tempId = $this->request->request("temp_id", "", "trim");
        if(empty($tempId)) $this->error("非法请求");
        $template = CsEmailTemplate::get($tempId);
        if(empty($template)) $this->error("模板不存在");
        if($template->status == CsEmailTemplate::IS_NO) $this->error("模板已关闭");
        $content = $this->replaceVar($template->content, $template->variable);
        if(empty($sn))
        {
            $this->success($content);
        }
        $order = Orders::whereRaw("order_sn=? OR order_no=?", [$sn, $sn])->find();
        if(empty($order)) $this->error("订单不存在");
        $content = $this->replaceVar($content, $order->toArray());
         $this->success('复制成功', '', $content);
    }

    /**
     * 替换模板变量值
     * @date 2020/12/10
     * @author longli
     */
    private function replaceVar($content, $data = [])
    {
        if(!empty($data))
        {
            $search = $replace = [];
            foreach($data as $k => $v)
            {
                $search[] = "\${{$k}}";
                $replace[] = $v;
            }
            $content = str_replace($search, $replace, $content);
        }
        return $content;
    }

    /**
     * 显示邮件模板变量
     * @return void
     * @date 2020/12/10
     * @author longli
     */
    public function show_var()
    {
        $this->assign("list", [
            [
                'var1' => 'order_no',
                'var1_name' => '平台订单号',
                'var2' => 'payment_method',
                'var2_name' => '支付方式',
                'var3' => 'logistics_name',
                'var3_name' => '物流商',
            ],
            [
                'var1' => 'logistics_price',
                'var1_name' => '物流费用',
                'var2' => 'weight',
                'var2_name' => '订单重量(g)',
                'var3' => 'customs_code',
                'var3_name' => '通关编码',
            ],
            [
                'var1' => 'track_num',
                'var1_name' => '追踪号',
                'var2' => 'discount_amount',
                'var2_name' => '订单优惠金额',
                'var3' => 'shipping_time',
                'var3_name' => '订单发货时间',
            ],
            [
                'var1' => 'order_source_create_time',
                'var1_name' => '订单在平台创建时间',
                'var2' => 'order_pay_time',
                'var2_name' => '订单在平台支付时间',
                'var3' => 'total_qty',
                'var3_name' => '订单总数量',
            ]
            ,
            [
                'var1' => 'order_price',
                'var1_name' => '订单金额',
                'var2' => 'total_price',
                'var2_name' => '订单总金额',
                'var3' => 'currency',
                'var3_name' => '订单币种',
            ],
            [
                'var1' => 'consignee',
                'var1_name' => '收货人',
                'var2' => 'buyer_first_name',
                'var2_name' => '买家first名称',
                'var3' => 'buyer_last_name',
                'var3_name' => '买家last名称',
            ],
            [
                'var1' => 'buyer_post_code',
                'var1_name' => '买家邮编',
                'var2' => 'buyer_phone',
                'var2_name' => '买家电话',
                'var3' => 'buyer_mobile',
                'var3_name' => '买家手机',
            ],
            [
                'var1' => 'buyer_account',
                'var1_name' => '买家账号',
                'var2' => 'buyer_email',
                'var2_name' => '买家邮箱',
                'var3' => 'buyer_country_code',
                'var3_name' => '买家国家',
            ],
            [
                'var1' => 'buyer_province',
                'var1_name' => '买家所在省/州',
                'var2' => 'buyer_city',
                'var2_name' => '买家所在市',
                'var3' => 'buyer_district',
                'var3_name' => '买家所在区',
            ],
            [
                'var1' => 'buyer_address_1',
                'var1_name' => '买家地址1',
                'var2' => 'buyer_address_3',
                'var2_name' => '买家地址2',
                'var3' => 'buyer_address_3',
                'var3_name' => '买家地址3',
            ]
            ,
            [
                'var1' => 'platform_remark',
                'var1_name' => '平台订单备注',
                'var2' => '',
                'var2_name' => '',
                'var3' => '',
                'var3_name' => '',
            ]
        ]);
        return $this->fetch("show_var");
    }

    /**
     * 加载共有变量信息
     * @date 2020/12/09
     * @author longli
     */
    protected function loadCommon()
    {
        $this->assign("country", SysCountries::getCodeNameCh());
        $this->assign("category", CsEmailCategory::getAllByTree());
    }

    /**
     * 更新分类信息
     * @date 2020/12/08
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'cate_id'  => 'require',
                'lang' => 'require',
                'content' => 'require',
            ],[
                'cate_id.require' => '分类必选',
                'lang.require' => '语言必选',
                'name.require' => '名称必填',
                'content.require' => '邮件内容必填',
            ]);
            $data = $this->request->post();
            $data['is_html'] = isset($data['is_html']) ? CsEmailTemplate::IS_NO : CsEmailTemplate::IS_YES;
            $data['content'] = $data['is_html'] ? $data['content_html'] : $data['content_text'];
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
            if(!isset($data['status'])) $data['status'] = CsEmailTemplate::IS_NO;
            if(!empty($data['keyword'])) $data['keyword'] = replaceStr($data['keyword']);
            $this->parseVar($data);
        }
        else
        {
            $validate = Validate::make([
                'temp_id'  => 'require',
            ],[
                'temp_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['temp_id', 'status'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        EmailService::getInstance()->addEmailTemplate($data)
            ? $this->redirect('index')
            : $this->error('操作失败');
    }

    /**
     * 解析模板变量
     * @return void
     * @date 2020/12/09
     * @author longli
     */
    private function parseVar(& $data = [])
    {
        if(isset($data['content']))
        {
            $data['content'] = str_replace(['￥{'], ['${'], $data['content']);
        }
        if(isset($data['var']))
        {
            $json = [];
            foreach($data['var'] as $k => $v)
            {
                if(Tools::isEmpty($v) || Tools::isEmpty($data['value'][$k])) continue;
                $json[$v] = $data['value'][$k];
            }
            $data['variable'] = $json;
        }
    }

    /**
     * 添加分类
     * @date 2020/12/08
     * @author longli
     */
    public function add()
    {
        $this->loadCommon();
        $tempId = $this->request->get("temp_id");
        if($tempId) $this->assign("template", CsEmailTemplate::get($tempId));
        return $this->fetch("add");
    }

    /**
     * 删除分类
     * @return void
     * @date 2020/12/08
     * @author longli
     */
    public function delete()
    {
        $tempId = $this->request->request("ids");
        if(empty($tempId)) $this->error('参数错误');
        CsEmailTemplate::destroy($tempId);
        $this->success('删除成功');
    }
}